<template>
  <el-form :model="dynamicValidateForm"
           ref="dynamicValidateForm"
           label-width="88px"
           class="demo-dynamic">
    <el-form-item :label="label">
      <el-input @blur="inputBlur" v-model="dynamicValidateForm.value"></el-input>
    </el-form-item>
    <el-form-item
      v-for="domain in dynamicValidateForm.domains"
      :key="domain.key">
      <el-row>
        <el-col :span="20">
          <el-input @blur="inputBlur" v-model="domain.value" />
        </el-col>
        <el-col :span="4" align="right">
          <el-button type="danger" @click.prevent="removeDomain(domain)">删除</el-button>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button @click="addDomain" type="primary">新增</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "dynamicValidateForm",
  props:{
    label:{
      type:String,
      required:true
    }
  },
  data() {
    return {
      dynamicValidateForm: {
        domains: [{
          value: ''
        }],
        value:""
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    removeDomain(item) {
      let index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
      this.inputBlur()
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: '',
        key: Date.now()
      });
    },
    inputBlur(){
      let arr = [this.dynamicValidateForm.value]
      this.dynamicValidateForm.domains.forEach(item => {
        if (item.value){
          arr.push(item.value)
        }
      })
      this.$emit('input',arr)
    }
  }
}
</script>

<style scoped>

</style>
